<template>
  <div class="report-generator">
    <el-tabs v-model="activeTab">
      <!-- 新建/编辑报表 -->
      <el-tab-pane label="新建/编辑报表" name="edit">
        <div v-if="!editing">
          <el-button type="primary" @click="openCreateDialog">新建报表</el-button>
        </div>
        <div v-else>
          <el-steps :active="step" finish-status="success" align-center>
            <el-step title="选择模板"></el-step>
            <el-step title="内容编辑"></el-step>
            <el-step title="导出设置"></el-step>
          </el-steps>
          <div v-show="step === 0" class="step-content">
            <el-radio-group v-model="currentReport.type">
              <el-radio label="日报">日报</el-radio>
              <el-radio label="周报">周报</el-radio>
              <el-radio label="月报">月报</el-radio>
            </el-radio-group>
            <el-button type="primary" @click="step++" style="margin-top: 20px;">下一步</el-button>
          </div>
          <div v-show="step === 1" class="step-content">
            <div class="drag-area">
              <div class="components-list">
                <div
                  v-for="comp in availableComponents"
                  :key="comp.type"
                  class="draggable-comp"
                  draggable
                  @dragstart="onDragStart(comp)"
                >
                  {{ comp.name }}
                </div>
              </div>
              <div
                class="drop-canvas"
                @dragover.prevent
                @drop="onDrop"
              >
                <div
                  v-for="(comp, idx) in currentReport.components"
                  :key="comp.id"
                  class="canvas-comp"
                >
                  <component
                    :is="comp.type"
                    :mock-data="mockData[comp.type]"
                  />
                  <el-button
                    type="text"
                    size="mini"
                    @click="removeComponent(idx)"
                  >移除</el-button>
                </div>
                <div v-if="!currentReport.components.length" class="canvas-placeholder">
                  拖拽左侧组件到此处
                </div>
              </div>
            </div>
            <div style="margin-top: 20px;">
              <el-form :inline="true" label-width="100px">
                <el-form-item label="数据更新频率">
                  <el-select v-model="currentReport.updateFreq" style="width: 160px;">
                    <el-option label="实时" value="realtime"></el-option>
                    <el-option label="每日凌晨" value="daily"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <el-button @click="step--">上一步</el-button>
            <el-button type="primary" @click="step++" :disabled="!currentReport.components.length">下一步</el-button>
          </div>
          <div v-show="step === 2" class="step-content">
            <el-form label-width="100px">
              <el-form-item label="导出格式">
                <el-checkbox-group v-model="currentReport.exportFormats">
                  <el-checkbox label="PDF"></el-checkbox>
                  <el-checkbox label="Excel"></el-checkbox>
                  <el-checkbox label="PPT"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="公司LOGO">
                <input type="file" @change="onLogoChange" />
                <img v-if="currentReport.logo" :src="currentReport.logo" style="max-width: 80px; margin-left: 10px;" />
              </el-form-item>
              <el-form-item label="页码">
                <el-switch v-model="currentReport.showPageNum"></el-switch>
              </el-form-item>
            </el-form>
            <el-button @click="step--">上一步</el-button>
            <el-button type="success" @click="saveReport">生成报表</el-button>
          </div>
        </div>
      </el-tab-pane>
      <!-- 历史报表 -->
      <el-tab-pane label="历史报表" name="history">
        <el-date-picker
          v-model="historyFilter"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-bottom: 20px;"
        />
        <el-table :data="filteredReports" style="width: 100%">
          <el-table-column prop="title" label="报表名称" />
          <el-table-column prop="type" label="类型" />
          <el-table-column prop="createdAt" label="创建时间" />
          <el-table-column prop="exportFormats" label="导出格式" :formatter="fmtExport" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="viewReport(scope.row)">查看</el-button>
              <el-button size="mini" @click="sendEmail(scope.row)">邮件推送</el-button>
              <el-button size="mini" type="danger" @click="deleteReport(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 新建报表对话框 -->
    <el-dialog title="新建报表" :visible.sync="createDialogVisible" width="400px">
      <el-form label-width="80px">
        <el-form-item label="报表名称">
          <el-input v-model="currentReport.title" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="startEdit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 报表预览对话框 -->
    <el-dialog title="报表预览" :visible.sync="previewDialogVisible" width="80%">
      <div>
        <h2>{{ previewReport.title }}</h2>
        <div v-for="comp in previewReport.components" :key="comp.id" style="margin-bottom: 20px;">
          <component :is="comp.type" :mock-data="mockData[comp.type]" />
        </div>
        <div v-if="previewReport.logo">
          <img :src="previewReport.logo" style="max-width: 120px;" />
        </div>
        <div v-if="previewReport.showPageNum" style="text-align: right;">第1页</div>
      </div>
      <div slot="footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'

// 设备运行状态看板组件
const DeviceStatusBoard = {
  props: ['mockData'],
  template: `
    <div class="device-status-board">
      <h3>设备运行状态看板</h3>
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in mockData" :key="item.name">
          <el-card>
            <div>{{item.name}}</div>
            <el-progress :percentage="item.status" :color="item.status === 100 ? '#13ce66' : '#ffba00'"></el-progress>
          </el-card>
        </el-col>
      </el-row>
    </div>
  `
}

// 故障统计表格组件
const FaultTable = {
  props: ['mockData'],
  template: `
    <div class="fault-table">
      <h3>故障统计表格</h3>
      <el-table :data="mockData" style="width: 100%">
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="faultCount" label="故障次数" />
        <el-table-column prop="lastFault" label="最近故障时间" />
      </el-table>
    </div>
  `
}

// 关键指标趋势图组件
const KeyMetricChart = {
  props: ['mockData'],
  mounted() {
    this.drawChart()
  },
  watch: {
    mockData() {
      this.drawChart()
    }
  },
  methods: {
    drawChart() {
      if (!this.$refs.canvas) return
      const ctx = this.$refs.canvas.getContext('2d')
      ctx.clearRect(0, 0, 400, 200)
      ctx.beginPath()
      ctx.moveTo(0, 200 - this.mockData[0])
      for (let i = 1; i < this.mockData.length; i++) {
        ctx.lineTo(i * (400 / this.mockData.length), 200 - this.mockData[i])
      }
      ctx.strokeStyle = '#409EFF'
      ctx.lineWidth = 2
      ctx.stroke()
    }
  },
  template: `
    <div class="key-metric-chart">
      <h3>关键指标趋势图</h3>
      <canvas ref="canvas" width="400" height="200" style="border:1px solid #eee"></canvas>
    </div>
  `
}

export default {
  name: 'VisualReportGeneration',
  components: {
    DeviceStatusBoard,
    FaultTable,
    KeyMetricChart
  },
  data() {
    return {
      activeTab: 'edit',
      editing: false,
      step: 0,
      createDialogVisible: false,
      previewDialogVisible: false,
      currentReport: {
        id: '',
        title: '',
        type: '日报',
        components: [],
        updateFreq: 'realtime',
        exportFormats: ['PDF'],
        logo: '',
        showPageNum: true,
        createdAt: '',
        emailSchedule: ''
      },
      availableComponents: [
        { type: 'DeviceStatusBoard', name: '设备运行状态看板' },
        { type: 'FaultTable', name: '故障统计表格' },
        { type: 'KeyMetricChart', name: '关键指标趋势图' }
      ],
      dragComp: null,
      reports: [],
      historyFilter: [],
      previewReport: {},
      mockData: {
        DeviceStatusBoard: [
          { name: '发电机', status: 100 },
          { name: '水轮机', status: 100 },
          { name: '变压器', status: 90 }
        ],
        FaultTable: [
          { device: '发电机', faultCount: 0, lastFault: '-' },
          { device: '水轮机', faultCount: 1, lastFault: '2024-06-01' },
          { device: '变压器', faultCount: 2, lastFault: '2024-05-28' }
        ],
        KeyMetricChart: [120, 130, 140, 135, 150, 145, 160, 155, 150, 148, 152, 158, 160, 162, 165, 170, 168, 165, 160, 158]
      }
    }
  },
  computed: {
    filteredReports() {
      if (!this.historyFilter || !this.historyFilter.length) return this.reports
      const [start, end] = this.historyFilter
      return this.reports.filter(r => {
        const t = new Date(r.createdAt).getTime()
        return t >= new Date(start).getTime() && t <= new Date(end).getTime()
      })
    }
  },
  created() {
    this.loadReports()
  },
  methods: {
    openCreateDialog() {
      this.currentReport = {
        id: '',
        title: '',
        type: '日报',
        components: [],
        updateFreq: 'realtime',
        exportFormats: ['PDF'],
        logo: '',
        showPageNum: true,
        createdAt: '',
        emailSchedule: ''
      }
      this.createDialogVisible = true
    },
    startEdit() {
      if (!this.currentReport.title) {
        Message.warning('请输入报表名称')
        return
      }
      this.currentReport.id = 'rpt_' + Date.now()
      this.createDialogVisible = false
      this.editing = true
      this.step = 0
    },
    onDragStart(comp) {
      this.dragComp = comp
    },
    onDrop() {
      if (this.dragComp) {
        this.currentReport.components.push({
          ...this.dragComp,
          id: 'comp_' + Date.now() + '_' + Math.random()
        })
        this.dragComp = null
      }
    },
    removeComponent(idx) {
      this.currentReport.components.splice(idx, 1)
    },
    onLogoChange(e) {
      const file = e.target.files[0]
      if (!file) return
      const reader = new FileReader()
      reader.onload = e2 => {
        this.currentReport.logo = e2.target.result
      }
      reader.readAsDataURL(file)
    },
    saveReport() {
      this.currentReport.createdAt = new Date().toISOString().slice(0, 19).replace('T', ' ')
      // 保存到本地
      let reports = JSON.parse(localStorage.getItem('reports') || '[]')
      reports.push({ ...this.currentReport })
      localStorage.setItem('reports', JSON.stringify(reports))
      this.loadReports()
      this.editing = false
      this.step = 0
      Message.success('报表已生成并保存')
    },
    loadReports() {
      this.reports = JSON.parse(localStorage.getItem('reports') || '[]')
    },
    fmtExport(row) {
      return (row.exportFormats || []).join('、')
    },
    viewReport(row) {
      this.previewReport = row
      this.previewDialogVisible = true
    },
    deleteReport(row) {
      MessageBox.confirm('确定删除该报表吗？', '提示', {
        type: 'warning'
      }).then(() => {
        let reports = JSON.parse(localStorage.getItem('reports') || '[]')
        reports = reports.filter(r => r.id !== row.id)
        localStorage.setItem('reports', JSON.stringify(reports))
        this.loadReports()
        Message.success('已删除')
      })
    },
    sendEmail(row) {
      MessageBox.prompt('请输入接收邮箱（模拟功能）', '邮件推送', {
        inputPattern: /^[\w-]+@[\w-]+\.[\w-]+$/,
        inputErrorMessage: '邮箱格式不正确'
      }).then(({ value }) => {
        // 这里只做模拟
        Message.success('已模拟推送到邮箱：' + value)
      })
    }
  }
}
</script>

<style scoped>
.report-generator {
  padding: 20px;
}
.step-content {
  margin: 30px 0;
}
.drag-area {
  display: flex;
  margin-bottom: 20px;
}
.components-list {
  width: 180px;
  border: 1px dashed #dcdfe6;
  padding: 10px;
  margin-right: 30px;
  background: #fafbfc;
  border-radius: 4px;
}
.draggable-comp {
  background: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: grab;
  text-align: center;
}
.drop-canvas {
  flex: 1;
  min-height: 220px;
  border: 2px dashed #b3c0d1;
  border-radius: 4px;
  background: #fff;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}
.canvas-comp {
  width: 420px;
  margin-right: 20px;
  margin-bottom: 20px;
  background: #f9f9f9;
  border-radius: 4px;
  box-shadow: 0 1px 4px #eee;
  padding: 10px;
  position: relative;
}
.canvas-placeholder {
  color: #bbb;
  font-size: 16px;
  text-align: center;
  width: 100%;
  margin-top: 60px;
}
</style>
